package com.passwordmanager.activities;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import com.passwordmanager.data.Password;
import com.passwordmanager.manager.DatabaseHelper;
import com.passwordmanager.utils.SimpleCrypto;

public class createPassword extends OrmLiteBaseActivity<DatabaseHelper>{
	Button validButton;
	EditText editTextPassword;
	EditText editTextConfirm;
	String password;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_password);
		validButton = (Button)findViewById(R.id.buttonValid);
		editTextPassword = (EditText)findViewById(R.id.editTextPassword);
		editTextConfirm = (EditText)findViewById(R.id.editTextConfirm);
		validButton.setOnClickListener(
				new OnClickListener() {	
					public void onClick(View v) {
						if (editTextPassword.getText() == null || editTextPassword.getText().length() == 0) {
							Toast.makeText(createPassword.this, getString(R.string.passwordRequired), Toast.LENGTH_LONG).show();
							return;
						} else if (!editTextPassword.getText().toString().equals(editTextConfirm.getText().toString())) {
							Toast.makeText(createPassword.this, getString(R.string.errorConfirm), Toast.LENGTH_LONG).show();
							return;
						} else {
							try {
								
								savePassword();
								//callPasswordManager();
							} catch (Exception e) {
								Log.e("Error", "Error");
							}
						}
					}
				}
		);
		
	}

	protected void callPasswordManager() {
		Intent intent = new Intent(createPassword.this, PasswordManager.class);
		intent.putExtra("password", password);
		startActivity(intent);
	}

	protected void savePassword() throws Exception {
		Dao<Password, Integer> passwordDao = getHelper().getPasswordDao();
		password = editTextPassword.getText().toString();
		String cryptPassword = SimpleCrypto.encrypt(password, password);
		passwordDao.create(new Password(cryptPassword));
		Toast.makeText(createPassword.this, getString(R.string.passwordCreateSuccess), Toast.LENGTH_LONG).show();
	}
}
